package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.OutputStreamWriter;

public class TimeHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        // 使用UTF-8编码的PrintWriter
        PrintWriter writer = new PrintWriter(
                new OutputStreamWriter(response, StandardCharsets.UTF_8),
                true
        );

        // 生成当前时间
        String currentTime = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // 构建响应内容
        String content = "<h1>MiniWebSvr Current Time</h1>" +
                "<p>Server Time: <strong>" + currentTime + "</strong></p>";

        // TODO: [222024321072035/万能] 构造完整的 HTTP 响应头和响应体
        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/html; charset=UTF-8");
        writer.println("Content-Length: " + content.getBytes(StandardCharsets.UTF_8).length);
        writer.println("Connection: close");
        writer.println();  // 空行分隔头和体

        // 发送响应体
        writer.println(content);
        writer.flush();
    }
}
